package com.zkthink.ceres.product.service.impl;

import com.zkthink.base.R;
import com.zkthink.database.mybatis.conditions.Wraps;
import com.zkthink.dozer.DozerUtils;
import com.zkthink.ceres.product.dao.ProductCategoryMapper;
import com.zkthink.ceres.product.dto.*;
import com.zkthink.ceres.product.entity.ProductCategory;
import com.zkthink.ceres.product.service.ProductCategoryService;
import com.zkthink.base.service.SuperServiceImpl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;
import java.util.*;

import com.zkthink.ceres.product.dao.ProductMapper;

/**
 * <p>
 * 业务实现类
 * 商品分类表
 * </p>
 *
 * @author JustArgo
 * @date 2020-05-03
 */
@Slf4j
@Service
public class ProductCategoryServiceImpl extends SuperServiceImpl<ProductCategoryMapper, ProductCategory> implements ProductCategoryService {

    @Autowired
    private ProductCategoryMapper productCategoryMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private DozerUtils dozerUtils;

    @Override
    public R<Boolean> addCategory(List<ProductCategoryDTO> dtoList) {
        if (dtoList == null || dtoList.size() == 0) {
            return R.fail("参数不正确");
        }

        String validate = validateCategory(dtoList);
        if(StringUtils.isNotBlank(validate)){
            return R.fail(validate);
        }

        for (ProductCategoryDTO dto : dtoList) {
            if (dto.getDepth() == 1 || dto.getDepth() == 2 || dto.getDepth() == 3) {
                ProductCategory productCategory = new ProductCategory();
                BeanUtils.copyProperties(dto, productCategory);
                productCategory.setSortOrder(1);
                productCategory.setIsDelete(0);
                productCategory.setStatus(1);
                productCategoryMapper.insert(productCategory);

                List<ProductCategoryDTO> childs = dto.getChilds();
                if (childs != null && childs.size() > 0) {
                    for (ProductCategoryDTO childDto : childs) {
                        childDto.setParentId(productCategory.getId());
                        childDto.setParentName(productCategory.getCategoryName());
                    }
                    R<Boolean> result = this.addCategory(childs);
                    if (result.getCode() != 0) {
                        return result;
                    }
                }
            } else {
                return R.fail("类目级别错误");
            }
        }

        return R.success(true);
    }

    @Override
    public R<Boolean> updateCategory(List<ProductCategoryDTO> dtoList) {
        if (dtoList == null) {
            return R.fail("参数不正确");
        }

        String validate = validateCategory(dtoList);
        if(StringUtils.isNotBlank(validate)){
            return R.fail(validate);
        }

        List<Long> idList = new ArrayList<Long>();
        for (ProductCategoryDTO dto : dtoList) {
            if(dto.getId()!=null && dto.getId()!=0){
                idList.add(dto.getId());
            }
        }

        int depth = -1;
        if(dtoList.size()>0){
            depth = dtoList.get(0).getDepth();
        }
        if(depth!=-1 && depth!=1){
            Long parentId = dtoList.get(0).getParentId();
            productCategoryMapper.delByDepthAndNotInIdList(parentId,depth,idList);
        }

        for (ProductCategoryDTO dto : dtoList) {
            if (dto.getDepth() == 1 || dto.getDepth() == 2 || dto.getDepth() == 3) {
                //修改
                if (dto.getId() != null && dto.getId() > 0) {
                    ProductCategory productCategory = new ProductCategory();
                    BeanUtils.copyProperties(dto, productCategory);
                    productCategory.setSortOrder(1);
                    productCategory.setStatus(1);
                    productCategory.setIsDelete(0);
                    productCategoryMapper.updateCategoryById(productCategory);

                    List<ProductCategoryDTO> childs = dto.getChilds();
                    if (childs != null && childs.size() > 0) {
                        for (ProductCategoryDTO childDto : childs) {
                            childDto.setParentId(productCategory.getId());
                            childDto.setParentName(productCategory.getCategoryName());
                        }
                        R<Boolean> result = this.updateCategory(childs);
                        if (result.getCode() != 0) {
                            return result;
                        }
                    }
                } else {//新增
                    ProductCategory productCategory = new ProductCategory();
                    BeanUtils.copyProperties(dto, productCategory);
                    productCategory.setSortOrder(1);
                    productCategory.setIsDelete(0);
                    productCategory.setStatus(1);
                    productCategoryMapper.insert(productCategory);

                    List<ProductCategoryDTO> childs = dto.getChilds();
                    if (childs != null && childs.size() > 0) {
                        for (ProductCategoryDTO childDto : childs) {
                            childDto.setParentId(productCategory.getId());
                            childDto.setParentName(productCategory.getParentName());
                        }
                        R<Boolean> result = this.addCategory(childs);
                        if (result.getCode() != 0) {
                            return result;
                        }
                    }
                }
            } else {
                return R.fail("类目级别错误");
            }
        }

        return R.success(true);
    }

    @Override
    public R<List<ProductCategoryDTO>> queryAllCategory() {
        List<ProductCategoryDTO> productCategoryList1 = productCategoryMapper.selectByDepth(1);
        List<ProductCategoryDTO> productCategoryList2 = productCategoryMapper.selectByDepth(2);
        List<ProductCategoryDTO> productCategoryList3 = productCategoryMapper.selectByDepth(3);

        Map<Long, List<ProductCategoryDTO>> parentIdCategoryListMap = new HashMap<Long, List<ProductCategoryDTO>>();
        for (ProductCategoryDTO cate : productCategoryList3) {
            List<ProductCategoryDTO> cateList = parentIdCategoryListMap.get(cate.getParentId());
            if (cateList == null) {
                cateList = new ArrayList<ProductCategoryDTO>();
                parentIdCategoryListMap.put(cate.getParentId(), cateList);
            }
            cateList.add(cate);
        }

        Map<Long, List<ProductCategoryDTO>> parentIdCategoryDTOListMap = new HashMap<Long, List<ProductCategoryDTO>>();
        for (ProductCategoryDTO cate : productCategoryList2) {
            List<ProductCategoryDTO> cateList = parentIdCategoryDTOListMap.get(cate.getParentId());
            if (cateList == null) {
                cateList = new ArrayList<ProductCategoryDTO>();
                parentIdCategoryDTOListMap.put(cate.getParentId(), cateList);
            }
            cate.setChilds(parentIdCategoryListMap.get(cate.getId()));
            cateList.add(cate);
        }

        List<ProductCategoryDTO> dtoList = new ArrayList<ProductCategoryDTO>();
        for (ProductCategoryDTO cate : productCategoryList1) {
            cate.setChilds(parentIdCategoryDTOListMap.get(cate.getId()));
            dtoList.add(cate);
        }

        return R.success(dtoList);
    }

    @Override
    public R<ProductCategoryDTO> queryOneCategory(IdQueryDTO dto) {
        ProductCategoryDTO cateDto = productCategoryMapper.selectDtoById(dto.getId());
        wrapperChildDTO(cateDto);
        return R.success(cateDto);
    }

    @Override
    public R<List<ProductCategoryDTO>> queryChildCategory(IdQueryDTO dto, boolean filterStatus) {
        List<ProductCategoryDTO> cateList = productCategoryMapper.selectDtoListByParentId(dto.getId(), filterStatus);
        for (ProductCategoryDTO childDto : cateList) {
            wrapperChildDTO(childDto);
        }
        return R.success(cateList);
    }

    @Override
    public R<List<ProductCategoryDTO>> findCategoryListByDepth(Integer depth, boolean filterStatus) {
        List<ProductCategory> productCategoryList = productCategoryMapper.selectList(Wraps.<ProductCategory>lbQ().eq(ProductCategory::getDepth, depth)
                                                                            .eq(ProductCategory::getIsDelete, 0)
                                                                            .eq(filterStatus, ProductCategory::getStatus, 1));
        List<ProductCategoryDTO> dtoList = dozerUtils.mapList(productCategoryList, ProductCategoryDTO.class);
        return R.success(dtoList);
    }

    @Override
    public R<AdminProductCategoryPageDTO> findPageCategory(PageQueryDTO pageQueryDTO) {

        if (pageQueryDTO == null || pageQueryDTO.getPageIndex() < 1 || pageQueryDTO.getPageSize() <= 0 || pageQueryDTO.getPageSize() > 200) {
            return R.fail("参数错误");
        }

        int total = this.count(Wraps.<ProductCategory>lbQ().eq(ProductCategory::getDepth, 1).eq(ProductCategory::getIsDelete, 0));

        pageQueryDTO.setStart((pageQueryDTO.getPageIndex()-1)*pageQueryDTO.getPageSize());
        List<ProductCategoryDTO> productCategoryList1 = productCategoryMapper.selectByDepthLimit(1, pageQueryDTO.getStart(), pageQueryDTO.getPageSize());

        AdminProductCategoryPageDTO pageDTO = new AdminProductCategoryPageDTO();
        pageDTO.setProductCategoryList(productCategoryList1);
        pageDTO.setTotal(total);

        return R.success(pageDTO);
    }

    @Override
    public R<Boolean> delCategory(Long categoryId, Integer depth) {
        //1. 根据类目查询商品的数量
        //2. 如果数量>0，返回错误信息，不让删除
        //3. 如果数量<=0，删除对应的类目

        List<Long> level3IdList = new ArrayList<Long>();
        List<Long> needDeletedIdList = new ArrayList<Long>();
        needDeletedIdList.add(categoryId);
        if (depth == 1) {
            List<Long> level2List = productCategoryMapper.selectCategoryIdByParentId(categoryId);
            if (level2List.size() > 0) {
                needDeletedIdList.addAll(level2List);
                level3IdList = productCategoryMapper.selectCategoryIdByParentIdList(level2List);
            }
        } else if (depth == 2) {
            level3IdList = productCategoryMapper.selectCategoryIdByParentId(categoryId);
        } else {
            level3IdList.add(categoryId);
        }

        //如果找到3级类目id，说明类目正常使用
        if (level3IdList.size() > 0) {
            Integer count = productMapper.selectCountByCategoryIdList(level3IdList);
            if (count > 0) {
                return R.fail(-1, "该类目已绑定商品，不能删除");
            }
        }

        needDeletedIdList.addAll(level3IdList);

        for (Long cateId : needDeletedIdList) {
            productCategoryMapper.delCategory(cateId);
        }

        return R.success();
    }

    /**
     * 给定一个productCategoryDTO 组装好它的childs
     *
     * @return
     * @author JustArgo 2020/5/10 16:56
     */
    private void wrapperChildDTO(ProductCategoryDTO dto) {
        if (dto == null || dto.getDepth() == 3) {
            return;
        }
        if (dto.getDepth() == 2) {
            List<ProductCategoryDTO> childList = productCategoryMapper.selectDtoListByParentId(dto.getId(),false);
            dto.setChilds(childList);
        }
        if (dto.getDepth() == 1) {
            List<ProductCategoryDTO> childList = productCategoryMapper.selectDtoListByParentId(dto.getId(),false);
            for (ProductCategoryDTO childDto : childList) {
                wrapperChildDTO(childDto);
            }
            dto.setChilds(childList);
        }
    }

    /** 校验类目的属性
     * @author 黄永宗 2020/6/4 11:53
     * @return
     */
    private String validateCategory(List<ProductCategoryDTO> categoryDTOList){
        String validateResult = "";
        if(categoryDTOList!=null){
            //校验类目名称
            for(ProductCategoryDTO dto:categoryDTOList){
                if(StringUtils.isBlank(dto.getCategoryName())){
                    return "类目名称不能为空";
                }
            }
            for(ProductCategoryDTO dto:categoryDTOList){
                if(dto.getChilds()!=null){
                    String tmpResult = validateCategory(dto.getChilds());
                    if(StringUtils.isNotBlank(tmpResult)){
                        validateResult = tmpResult;
                    }
                }
            }

            //三级类目必须上传图片
            for(ProductCategoryDTO dto:categoryDTOList){
                if(dto.getDepth()!=null && dto.getDepth()==3 && StringUtils.isBlank(dto.getCategoryImg())){
                    validateResult = "三级类目必须上传图片";
                }
            }
        }
        return validateResult;
    }

}
